package service.wx

import org.apache.commons.codec.digest.DigestUtils
import com.alibaba.fastjson.JSON

import org.paic.util.PropHelper

import org.slf4j.Logger
import org.slf4j.LoggerFactory

// 微信公众号服务签名相关
class WxSignature {
	static Logger log = LoggerFactory.getLogger(WxSignature.class)

	final static String CONF_FILE = '/config/wx.properties'

	// access token缓存时间
	static long lastAccessTimeAccessToken = 0
	// js sdk ticket缓存时间
	static long lastAccessTimeSign = 0

	static Map cached = [:]

	// wexin shi 7200
	static long expiredMillis = 1000 * 7000

	// 微信公众号的app信息
	static Properties conf = PropHelper.loadProperties(CONF_FILE)

	static void refreshConf(){
		conf = PropHelper.loadProperties(CONF_FILE)
	}

	static String getAccessToken(){
		String accessToken
		boolean isExpired = (System.currentTimeMillis() - lastAccessTimeAccessToken) > expiredMillis
		if(isExpired){
			String urlGetAccessToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${conf.appid}&secret=${conf.secret}"
			def objResult = JSON.parseObject(new URL(urlGetAccessToken).text)
			accessToken = objResult.access_token

			cached.accessToken = accessToken
			lastAccessTimeAccessToken = System.currentTimeMillis()

			log.info('get access token from weixin')
		}else{
			accessToken = cached.accessToken

			log.info('get access token from cache')
		}

		accessToken
	}

	// 生成微信jssdk页面的必要的签名信息
	static Map<String, String> sign(String url){
		boolean isExpired = (System.currentTimeMillis() - lastAccessTimeSign) > expiredMillis
		String ticket
		if(isExpired){
			String accessToken = getAccessToken()

			String urlGetJsapiTicket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${accessToken}&type=jsapi"
			def objResult = JSON.parseObject(new URL(urlGetJsapiTicket).text)
			ticket = objResult.ticket

			cached.ticket = ticket
			lastAccessTimeSign = System.currentTimeMillis()

			log.info('get ticket from weixin')
		}else{
			ticket = cached.ticket
			
			log.info('get ticket from cache')
		}
		
		String timestamp = '' + System.currentTimeMillis()
		timestamp = timestamp[0..-4]

		String str = "jsapi_ticket=${ticket}&noncestr=${conf.nonce}&timestamp=${timestamp}&url=${url}"
		String signature = DigestUtils.shaHex(str)

		[signature: signature, timestamp: timestamp, nonce: conf.nonce, appid: conf.appid]
	}
}